package com.example.sensor.slice;

import com.example.sensor.ResourceTable;
import com.example.sensor.Utils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.sensor.agent.CategoryMotionAgent;
import ohos.sensor.agent.CategoryOrientationAgent;
import ohos.sensor.agent.SensorAgent;
import ohos.sensor.bean.CategoryMotion;
import ohos.sensor.bean.CategoryOrientation;
import ohos.sensor.data.CategoryMotionData;
import ohos.sensor.data.CategoryOrientationData;
import ohos.sensor.listener.ICategoryMotionDataCallback;
import ohos.sensor.listener.ICategoryOrientationDataCallback;

public class AccelerometerAbilitySlice extends AbilitySlice {

    // 显示加速度的文本组件
    private Text mTextAccelerometer;
    // 运动类传感器代理
    private CategoryMotionAgent mMotionAgent;
    // 运动类传感器对象
    private CategoryMotion mMotion;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_accelerometer);
        // 初始化显示加速度的文本组件
        mTextAccelerometer = (Text) findComponentById(ResourceTable.Id_text_accelerometer);
        mTextAccelerometer.setMultipleLine(true); // 支持多行显示

        // 创建运动类传感器的代理对象
        mMotionAgent = new CategoryMotionAgent();
        // 获取加速度传感器
        mMotion = mMotionAgent.getSingleSensor(
                CategoryMotion.SENSOR_TYPE_ACCELEROMETER);
        // 订阅加速度传感器
        mMotionAgent.setSensorDataCallback(
                mMotionDataCallback, mMotion, SensorAgent.SENSOR_SAMPLING_RATE_UI);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 退订加速度传感器
        mMotionAgent.releaseSensorDataCallback(
                mMotionDataCallback, mMotion);
    }


    // 运动类传感器数据回调
    private ICategoryMotionDataCallback mMotionDataCallback = new ICategoryMotionDataCallback() {
        @Override
        public void onSensorDataModified(CategoryMotionData categoryMotionData) {
            final float[] values = categoryMotionData.values;
            getUITaskDispatcher().asyncDispatch(()-> {
                mTextAccelerometer.setText("X方向上的加速度:" + values[0]
                        + "\nY方向上的加速度:" + values[1]
                        + "\nZ方向上的加速度:" + values[2]);
            });

        }

        @Override
        public void onAccuracyDataModified(CategoryMotion categoryMotion, int i) {

        }

        @Override
        public void onCommandCompleted(CategoryMotion categoryMotion) {

        }
    };
}
